package com.bigdata.hadoop.mapreduce.wordcount;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

import java.io.IOException;

public class WordCountDriver {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf = new Configuration(); // 1 获取配置信息以及获取job对象
        if (args.length != 2) {
            System.err.println("Usage:wordcount <input><output>");
            System.exit(2);
        }
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();

        // 输出路径
        Path path = new Path(otherArgs[1]);
        FileSystem fileSystem = path.getFileSystem(conf);
        if (fileSystem.exists(path)) {
            fileSystem.delete(path, true);
        }

//        Job job = Job.getInstance();
        Job job = Job.getInstance(conf);

        job.setJarByClass(WordCountDriver.class);  // 2 关联本Driver程序的jar

        job.setMapperClass(WordCountMapper.class);  // 3 关联Mapper和Reducer的jar
        job.setCombinerClass(WordCountReducer.class); // 聚合操作
        job.setReducerClass(WordCountReducer.class);// 4. reducer操作输出

        job.setMapOutputKeyClass(Text.class);  // 4 设置Mapper输出的kv类型
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(Text.class);  // 5 设置最终输出kv类型
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.setInputPaths(job, new Path(args[0]));  // 6 设置输入和输出路径
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        boolean result = job.waitForCompletion(true);  // 7 提交job
        System.exit(result ? 0 : 1);
    }
}
